<template>
  <div class="voice-setting-container">
    <div class="header">
      <h1>语音设置</h1>
      <button class="btn btn-secondary" @click="resetToDefault">恢复默认</button>
    </div>

    <div class="voice-setting-content">
      <!-- 语音选择 -->
      <div class="setting-section">
        <h2>语音选择</h2>
        <div class="voice-selector">
          <div class="voice-option" 
               v-for="voice in availableVoices" 
               :key="voice.id"
               :class="{ active: currentVoice.id === voice.id }"
               @click="selectVoice(voice)"
          >
            <div class="voice-info">
              <div class="voice-name">{{ voice.name }}</div>
              <div class="voice-lang">{{ voice.languageName }}</div>
            </div>
            <button class="play-voice-btn" @click.stop="previewVoice(voice)">
              <i class="fa fa-volume-up"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 语音参数调整 -->
      <div class="setting-section">
        <h2>语音参数</h2>
        <div class="voice-parameters">
          <!-- 音调调整 -->
          <div class="parameter-group">
            <label for="pitch">音调</label>
            <div class="parameter-controls">
              <input
                type="range"
                id="pitch"
                min="-20"
                max="20"
                step="1"
                v-model.number="voiceParams.pitch"
                @input="updateVoiceParam('pitch', $event.target.value)"
              />
              <span class="parameter-value">{{ voiceParams.pitch }}</span>
            </div>
            <div class="parameter-preview">
              <button class="btn btn-sm btn-primary" @click="previewCurrentVoice">预览</button>
            </div>
          </div>

          <!-- 语速调整 -->
          <div class="parameter-group">
            <label for="speakingRate">语速</label>
            <div class="parameter-controls">
              <input
                type="range"
                id="speakingRate"
                min="0.5"
                max="2.0"
                step="0.1"
                v-model.number="voiceParams.speakingRate"
                @input="updateVoiceParam('speakingRate', $event.target.value)"
              />
              <span class="parameter-value">{{ voiceParams.speakingRate.toFixed(1) }}</span>
            </div>
            <div class="parameter-preview">
              <button class="btn btn-sm btn-primary" @click="previewCurrentVoice">预览</button>
            </div>
          </div>

          <!-- 音量调整 -->
          <div class="parameter-group">
            <label for="volumeGainDb">音量</label>
            <div class="parameter-controls">
              <input
                type="range"
                id="volumeGainDb"
                min="-96"
                max="16"
                step="1"
                v-model.number="voiceParams.volumeGainDb"
                @input="updateVoiceParam('volumeGainDb', $event.target.value)"
              />
              <span class="parameter-value">{{ voiceParams.volumeGainDb }} dB</span>
            </div>
            <div class="parameter-preview">
              <button class="btn btn-sm btn-primary" @click="previewCurrentVoice">预览</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 应用设置 -->
      <div class="setting-section">
        <h2>应用设置</h2>
        <div class="app-settings">
          <div class="setting-item">
            <label class="setting-label">
              <input
                type="checkbox"
                v-model="appSettings.autoPlayPronunciation"
                @change="updateAppSetting('autoPlayPronunciation', $event.target.checked)"
              />
              <span>自动播放单词发音</span>
            </label>
            <p class="setting-description">在学习过程中自动播放单词的发音</p>
          </div>

          <div class="setting-item">
            <label class="setting-label">
              <input
                type="checkbox"
                v-model="appSettings.preloadAudio"
                @change="updateAppSetting('preloadAudio', $event.target.checked)"
              />
              <span>预加载音频</span>
            </label>
            <p class="setting-description">提前加载下一个单词的音频，减少播放延迟</p>
          </div>

          <div class="setting-item">
            <label class="setting-label">
              <input
                type="checkbox"
                v-model="appSettings.enableCache"
                @change="updateAppSetting('enableCache', $event.target.checked)"
              />
              <span>启用音频缓存</span>
            </label>
            <p class="setting-description">缓存已播放的音频，提高播放速度</p>
          </div>

          <div class="setting-item">
            <label for="cacheSizeLimit">缓存大小限制 (MB)</label>
            <input
              type="number"
              id="cacheSizeLimit"
              min="10"
              max="500"
              step="10"
              v-model.number="appSettings.cacheSizeLimit"
              @input="updateAppSetting('cacheSizeLimit', $event.target.value)"
            />
          </div>
        </div>
      </div>

      <!-- 缓存管理 -->
      <div class="setting-section">
        <h2>缓存管理</h2>
        <div class="cache-info">
          <p>当前缓存大小: <strong>{{ cacheSize }} MB</strong></p>
          <p>缓存文件数量: <strong>{{ cacheFileCount }}</strong></p>
        </div>
        <div class="cache-actions">
          <button class="btn btn-danger" @click="clearCache">清除缓存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useConfigStore } from '../../store'
import { textToSpeechAPI, voiceSettingAPI } from '../../services/apiService'

export default {
  name: 'VoiceSetting',
  setup() {
    const configStore = useConfigStore()
    
    // 状态管理
    const availableVoices = ref([])
    const currentVoice = ref({ id: 'en-US-Wavenet-C', name: 'English (US) - Female', languageName: '英语(美国)' })
    const isPlayingPreview = ref(false)
    
    // 缓存信息
    const cacheSize = ref(0)
    const cacheFileCount = ref(0)
    
    // 语音参数
    const voiceParams = ref({
      pitch: 0,
      speakingRate: 1.0,
      volumeGainDb: 0
    })
    
    // 应用设置
    const appSettings = ref({
      autoPlayPronunciation: true,
      preloadAudio: false,
      enableCache: true,
      cacheSizeLimit: 100
    })
    
    // 初始化数据
    const initializeData = async () => {
      try {
        // 获取可用语音列表（模拟）
        await loadAvailableVoices()
        // 加载当前设置
        loadCurrentSettings()
        // 获取缓存信息
        updateCacheInfo()
      } catch (error) {
        console.error('初始化语音设置失败', error)
      }
    }
    
    // 加载可用语音列表
    const loadAvailableVoices = async () => {
      try {
        // 模拟数据 - 实际项目中应从API获取
        availableVoices.value = generateMockVoices()
        
        // 实际API调用代码
        // const response = await textToSpeechAPI.getAvailableVoices()
        // availableVoices.value = response.data || []
      } catch (error) {
        console.error('获取可用语音失败', error)
      }
    }
    
    // 加载当前设置
    const loadCurrentSettings = () => {
      // 从store中加载设置
      if (configStore.voiceSettings) {
        currentVoice.value = {
          id: configStore.voiceSettings.voiceId,
          // 查找对应的语音名称和语言
          ...availableVoices.value.find(v => v.id === configStore.voiceSettings.voiceId) || {
            name: 'English (US) - Female',
            languageName: '英语(美国)'
          }
        }
        
        voiceParams.value = {
          pitch: configStore.voiceSettings.pitch || 0,
          speakingRate: configStore.voiceSettings.speakingRate || 1.0,
          volumeGainDb: configStore.voiceSettings.volumeGainDb || 0
        }
      }
      
      if (configStore.appSettings) {
        appSettings.value = {
          ...appSettings.value,
          ...configStore.appSettings
        }
      }
    }
    
    // 生成模拟语音数据
    const generateMockVoices = () => {
      return [
        { id: 'en-US-Wavenet-C', name: 'English (US) - Female', languageName: '英语(美国)' },
        { id: 'en-US-Wavenet-B', name: 'English (US) - Male', languageName: '英语(美国)' },
        { id: 'en-GB-Wavenet-B', name: 'English (UK) - Male', languageName: '英语(英国)' },
        { id: 'en-GB-Wavenet-C', name: 'English (UK) - Female', languageName: '英语(英国)' },
        { id: 'zh-CN-Wavenet-A', name: 'Chinese (Mainland) - Female', languageName: '中文(中国大陆)' },
        { id: 'zh-CN-Wavenet-B', name: 'Chinese (Mainland) - Male', languageName: '中文(中国大陆)' },
        { id: 'ja-JP-Wavenet-A', name: 'Japanese - Female', languageName: '日语' },
        { id: 'ja-JP-Wavenet-B', name: 'Japanese - Male', languageName: '日语' },
        { id: 'ko-KR-Wavenet-A', name: 'Korean - Female', languageName: '韩语' },
        { id: 'ko-KR-Wavenet-B', name: 'Korean - Male', languageName: '韩语' },
        { id: 'fr-FR-Wavenet-A', name: 'French - Female', languageName: '法语' },
        { id: 'fr-FR-Wavenet-B', name: 'French - Male', languageName: '法语' },
        { id: 'de-DE-Wavenet-A', name: 'German - Female', languageName: '德语' },
        { id: 'de-DE-Wavenet-B', name: 'German - Male', languageName: '德语' },
        { id: 'es-ES-Wavenet-A', name: 'Spanish - Female', languageName: '西班牙语' },
        { id: 'es-ES-Wavenet-B', name: 'Spanish - Male', languageName: '西班牙语' }
      ]
    }
    
    // 更新缓存信息
    const updateCacheInfo = () => {
      // 模拟缓存数据
      cacheSize.value = Math.round(Math.random() * 50) + 10
      cacheFileCount.value = Math.round(Math.random() * 200) + 50
    }
    
    // 选择语音
    const selectVoice = async (voice) => {
      if (isPlayingPreview.value) return
      
      try {
        currentVoice.value = voice
        
        // 保存语音设置到store
        configStore.updateVoiceSettings({
          voiceId: voice.id,
          ...voiceParams.value
        })
        
        // 实际API调用代码 - 保存到后端
        // await voiceSettingAPI.updateVoiceSetting('default', {
        //   voiceId: voice.id,
        //   ...voiceParams.value
        // })
      } catch (error) {
        console.error('选择语音失败', error)
      }
    }
    
    // 更新语音参数
    const updateVoiceParam = async (param, value) => {
      try {
        const numericValue = parseFloat(value)
        voiceParams.value[param] = numericValue
        
        // 保存到store
        configStore.updateVoiceSettings({
          voiceId: currentVoice.value.id,
          ...voiceParams.value
        })
        
        // 实际API调用代码 - 保存到后端
        // await voiceSettingAPI.updateVoiceSetting('default', {
        //   voiceId: currentVoice.value.id,
        //   ...voiceParams.value
        // })
      } catch (error) {
        console.error('更新语音参数失败', error)
      }
    }
    
    // 更新应用设置
    const updateAppSetting = async (setting, value) => {
      try {
        appSettings.value[setting] = value
        
        // 保存到store
        configStore.updateAppSettings({
          ...appSettings.value
        })
        
        // 实际项目中可以选择将应用设置保存到后端
      } catch (error) {
        console.error('更新应用设置失败', error)
      }
    }
    
    // 预览语音
    const previewVoice = async (voice) => {
      if (isPlayingPreview.value) return
      
      try {
        isPlayingPreview.value = true
        
        // 模拟预览语音
        // 实际API调用代码
        // await textToSpeechAPI.synthesizeText('Hello, this is a voice preview', {
        //   voiceId: voice.id,
        //   ...voiceParams.value
        // })
        
        // 模拟播放延迟
        setTimeout(() => {
          isPlayingPreview.value = false
        }, 1500)
      } catch (error) {
        console.error('预览语音失败', error)
        isPlayingPreview.value = false
      }
    }
    
    // 预览当前语音设置
    const previewCurrentVoice = async () => {
      await previewVoice(currentVoice.value)
    }
    
    // 清除缓存
    const clearCache = async () => {
      if (confirm('确定要清除所有缓存吗？这将重新下载已缓存的音频文件。')) {
        try {
          // 实际API调用代码
          // await textToSpeechAPI.clearCache()
          
          // 模拟清除缓存
          cacheSize.value = 0
          cacheFileCount.value = 0
          
          // 可以添加成功提示
          alert('缓存已清除')
        } catch (error) {
          console.error('清除缓存失败', error)
        }
      }
    }
    
    // 恢复默认设置
    const resetToDefault = async () => {
      if (confirm('确定要恢复默认语音设置吗？')) {
        try {
          // 默认设置
          const defaultVoice = availableVoices.value.find(v => v.id === 'en-US-Wavenet-C') || availableVoices.value[0]
          const defaultParams = {
            pitch: 0,
            speakingRate: 1.0,
            volumeGainDb: 0
          }
          const defaultAppSettings = {
            autoPlayPronunciation: true,
            preloadAudio: false,
            enableCache: true,
            cacheSizeLimit: 100
          }
          
          // 更新本地状态
          currentVoice.value = defaultVoice
          voiceParams.value = defaultParams
          appSettings.value = defaultAppSettings
          
          // 保存到store
          configStore.updateVoiceSettings({
            voiceId: defaultVoice.id,
            ...defaultParams
          })
          
          configStore.updateAppSettings(defaultAppSettings)
          
          // 实际API调用代码 - 保存到后端
          // await voiceSettingAPI.updateVoiceSetting('default', {
          //   voiceId: defaultVoice.id,
          //   ...defaultParams
          // })
          
          // 可以添加成功提示
          alert('已恢复默认设置')
        } catch (error) {
          console.error('恢复默认设置失败', error)
        }
      }
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      initializeData()
    })
    
    return {
      availableVoices,
      currentVoice,
      isPlayingPreview,
      voiceParams,
      appSettings,
      cacheSize,
      cacheFileCount,
      selectVoice,
      updateVoiceParam,
      updateAppSetting,
      previewVoice,
      previewCurrentVoice,
      clearCache,
      resetToDefault
    }
  }
}
</script>

<style scoped>
.voice-setting-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #333;
  margin: 0;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background-color: #7f8c8d;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background-color: #c0392b;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

/* 设置区域样式 */
.setting-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 30px;
}

.setting-section h2 {
  color: #333;
  margin: 0 0 20px 0;
  font-size: 18px;
}

/* 语音选择器样式 */
.voice-selector {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

.voice-option {
  background: #f9f9f9;
  border: 2px solid transparent;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.voice-option:hover {
  background: #f0f0f0;
  border-color: #e0e0e0;
}

.voice-option.active {
  background: #e3f2fd;
  border-color: #3498db;
}

.voice-info {
  flex: 1;
}

.voice-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.voice-lang {
  font-size: 12px;
  color: #666;
}

.play-voice-btn {
  background: #3498db;
  color: white;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.play-voice-btn:hover {
  background: #2980b9;
}

/* 语音参数样式 */
.voice-parameters {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.parameter-group {
  display: flex;
  align-items: center;
  gap: 20px;
}

.parameter-group label {
  width: 100px;
  font-weight: 500;
  color: #333;
}

.parameter-controls {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 15px;
}

.parameter-controls input[type="range"] {
  flex: 1;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  -webkit-appearance: none;
}

.parameter-controls input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #3498db;
  cursor: pointer;
}

.parameter-controls input[type="range"]::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #3498db;
  cursor: pointer;
  border: none;
}

.parameter-value {
  min-width: 50px;
  text-align: right;
  font-weight: 500;
  color: #333;
}

.parameter-preview {
  width: 80px;
}

/* 应用设置样式 */
.app-settings {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.setting-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.setting-label {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 500;
  color: #333;
  cursor: pointer;
}

.setting-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.setting-description {
  color: #666;
  font-size: 14px;
  margin: 0 0 0 28px;
}

.setting-item input[type="number"] {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  width: 120px;
}

.setting-item input[type="number"]:focus {
  outline: none;
  border-color: #3498db;
}

/* 缓存管理样式 */
.cache-info {
  margin-bottom: 20px;
}

.cache-info p {
  margin: 8px 0;
  color: #333;
}

.cache-actions {
  display: flex;
  gap: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .setting-section {
    padding: 20px;
  }
  
  .voice-selector {
    grid-template-columns: 1fr;
  }
  
  .parameter-group {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .parameter-group label {
    width: auto;
  }
  
  .parameter-preview {
    width: auto;
  }
  
  .cache-actions {
    flex-direction: column;
  }
}
</style>